package com.franklin.ideaplugin.easytesting.thread.pressuretest;

import com.alibaba.fastjson2.JSON;
import com.franklin.ideaplugin.easytesting.rpc.RpcClient;
import com.franklin.ideaplugin.easytesting.rpc.entity.MethodInvokeData;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.io.IOException;

/**
 * 压力测试任务
 *
 * @author Ye Junhui
 * @since 2023/11/4
 */
@RequiredArgsConstructor
@Getter
public class PressureTestTask implements Runnable {

    private final String port;
    private final MethodInvokeData methodInvokeData;
    private final Integer loopCount;
    private final IPressureTestTaskNotifier pressureTestTaskNotifier;

    /**
     * 运行状态
     */
    private volatile boolean running = true;

    public void stop() {
        this.running = false;
    }

    @Override
    public void run() {
        methodInvokeData.setTxRollbackCover(false);
        methodInvokeData.setExecutePath(null);
        String body = JSON.toJSONString(methodInvokeData);
        for (int i = 0; running && i < loopCount; i++) {
            try {
                RpcClient.sendExecuteBlock(
                        body,
                        this.port,
                        System.out::println
                );
            } catch (IOException e) {
                e.printStackTrace();
                this.stop();
            }

            //通知一次任务完成
            this.pressureTestTaskNotifier.notifyFinishOneLoop(i);
        }
        //通知所有任务完成
        this.pressureTestTaskNotifier.notifyFinishAll();

        //任务结束
        this.stop();
    }
}
